<template>
<div style="width:98%;margin-left:1%;display:block">
    <div style="margin-top:1%;margin-bottom:1%;float:right">
        <product-form @update-list="updateList"/>
    </div>
    <div style="clear:right;margin-left:1%">
    <a-table :columns="columns" :data-source="data" bordered :scroll="{y:530}">
    <template
      v-for="col in ['productid', 'category', 'name','description']"
      :slot="col"
      slot-scope="text, record, index"
    >
      <div :key="col">
        <a-input
          v-if="record.editable"
          style="margin: -5px 0"
          :value="text"
          @change="e => handleChange(e.target.value, record.key, col)"
        />
        <template v-else>
          {{ text }}
        </template>
      </div>
    </template>
    <template slot="operation" slot-scope="text, record, index">
      <div class="editable-row-operations">
        <span v-if="record.editable">
          <a @click="() => save(record.key)">保存</a>
          <a-popconfirm title="确定取消吗?" @confirm="() => cancel(record.key)">
            <a>取消</a>
          </a-popconfirm>
        </span>
        <span v-else>
          <a :disabled="editingKey !== ''" @click="() => edit(record.key)">编辑</a>
        </span>
        <a-popconfirm  title="确定删除吗?" @confirm="() => onDelete(record.key)">
            <span>
              <a href="javascript:;">删除</a>
            </span>
          </a-popconfirm>
      </div>
    </template>
  </a-table>
  </div>
</div>
</template>
<script>
import ProductForm from '@/components/productForm.vue';
import { mapActions, mapState } from 'vuex'

const columns = [
  {
    title: '商品编号',
    dataIndex: 'productId',
    width: '15%',
    scopedSlots: { customRender: 'productId' },
  },
  {
    title: '所属类别',
    dataIndex: 'categoryId',
    width: '15%',
    scopedSlots: { customRender: 'categoryId' },
  },
  {
    title: '名称',
    dataIndex: 'name',
    width: '20%',
    scopedSlots: { customRender: 'name' },
  },
  {
    title: '描述',
    dataIndex: 'description',
    width: '35%',
    scopedSlots: { customRender: 'description' },
  },
  {
    title: '操作',
    dataIndex: 'operation',
    scopedSlots: { customRender: 'operation' },
  },
];

let data = [];

export default {
    components:{
        ProductForm,
    },
  data() {
    return {
      data,
      columns,
      editingKey: '',
    };
  },
  computed: {
    ...mapState({
      signIn: state => state.account.signIn,
      account: state => state.account.account
    })
  },
  methods: {
    ...mapActions({
      getProductList: 'product/getProductList',
      updateProduct: 'product/updateProduct',
      deleteProduct: 'product/deleteProduct',
      addProduct: 'product/addProduct',
    }),
    handleChange(value, key, column) {
      const newData = [...this.data];
      const target = newData.filter(item => key === item.key)[0];
      if (target) {
        target[column] = value;
        this.data = newData;
      }
    },
    onDelete(key) {
        // 拷贝数组数据
        let deleteD = this.data[key]
        let dataSource = [...this.data];
        // 过滤移除当前项目
        this.data = dataSource.filter(item => item.key !== key);
        this.deleteProduct({productId:deleteD.productId}).then((res)=>{
          this.openNotification("OK","删除商品信息成功",res)
        },(error)=>{
          this.openNotification("NOK","删除商品信息失败",error)
        })
      },
    edit(key) {
      const newData = [...this.data];
      const target = newData.filter(item => key === item.key)[0];
      this.editingKey = key;
      if (target) {
        target.editable = true;
        this.data = newData;
      }
    },
    save(key) {
      const newData = [...this.data];
      const target = newData.filter(item => key === item.key)[0];
      if (target) {
        delete target.editable;
        this.data = newData;
        Object.assign(target);
      }
      let newD = this.data[key]
      this.updateProduct({productId:newD.productId,category:newD.categoryId,name:newD.name,description:newD.description}).then((res)=>{
        this.cacheData = data.map(item => ({ ...item }));
        this.openNotification("OK","更新商品信息成功",res)
      }, (error) => {
        this.openNotification("NOK","更新商品信息失败",error)
      })
      this.editingKey = '';
    },
    cancel(key) {
      const newData = [...this.data];
      const target = newData.filter(item => key === item.key)[0];
      this.editingKey = '';
      if (target) {
        Object.assign(target,this.cacheData.filter(item => key === item.key)[0]);
        delete target.editable;
        this.data = newData;
      }
    },
    updateList() {
      this.getProductList({type: 'search', id:''}).then((res) => {
        let i = 0
        data.length = 0
        for(let item of res){
            item.key = i++
            data.push(item);
        }
        this.cacheData = data.map(item => ({ ...item }));
        this.openNotification("OK","更新商品列表成功","商品列表已更新!")
      }, (error) => {
        this.openNotification("NOK","更新商品列表失败",error)
      })
    },
    openNotification(type,title,msg) {
      let iconType = ''
      let iconColor = ''
      if(type=='OK'){
        iconType = 'smile'
        iconColor = '#52c41a'
      }
      else
      {
        iconType = 'frown'
        iconColor = '#eb2f96'
      }
      this.$notification.open({
        message: title,
        description: msg,
        icon: h => h('a-icon', {
          props: {
            type: iconType,
            theme: 'twoTone',
            'two-tone-color': iconColor
          }
        }),

      });
    }
  },
  mounted() {
    if(this.signIn===false||this.account===null){
      this.openNotification("NOK","未登录","请先登录管理员账号!")
      this.$router.push("/mainPage/login")
    }
    else{
      this.updateList()
    }
  }
};
</script>
<style lang="scss" scoped>
.editable-row-operations a {
  margin-right: 8px;
}
</style>
